package com.indi.gulimall.seckill.interceptor;

import com.indi.common.constant.AuthConstant;
import com.indi.common.to.MemberTO;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginUserInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberTO> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        // 此类型的请求，直接放行，无需登录，否则会报错
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();

        boolean match = antPathMatcher.match("/web/seckill/kill", uri);

        if (match) {
            MemberTO memberTO = (MemberTO) request.getSession().getAttribute(AuthConstant.SESSION_ATTR_NAME);
            if (memberTO != null) {
                threadLocal.set(memberTO);
                return true;
            } else {
                request.getSession().setAttribute("msg", "请先进行登录！");
                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;
            }
        }
        return true;
    }
}
